package de.fhhof.robot.control;


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import de.fhhof.robot.control.common.Utility;



public class MessageIdGenerator {

	private static long currentTime =0;
	
	private static AtomicInteger serial = new AtomicInteger(0);
	private static AtomicLong no = new AtomicLong(0);
	
	private static final int MESSAGE_PREFIX_LENGTH = 10;
	private static final int MESSAGE_POSTFIX_LENGTH = 2;
	
	
	public static synchronized String getNextMessageId(){
		String msgId = "";
		long currTime = System.currentTimeMillis()/1000;

		
		if(currTime == currentTime && serial.intValue() <99){
			serial.getAndIncrement();
		}
		else if(currTime == currentTime && serial.intValue() >= 99){
			try{
				Thread.sleep(1000);
				
			}catch(Exception ex){
				
			}
			currTime = System.currentTimeMillis()/1000;
			serial = new AtomicInteger(0);
		}
		else{
			serial = new AtomicInteger(0);
		}
		
		String prefix = Utility.leftPad(""+currTime+"", "0", MESSAGE_PREFIX_LENGTH);
		String postfix = "";
		postfix = Utility.leftPad(serial+"", "0", MESSAGE_POSTFIX_LENGTH);
		
		msgId = prefix +":"+  postfix;
		MessageIdGenerator.currentTime = currTime;
		
		return msgId;
	}
	public static synchronized Long getNextLongNo(){

		return no.getAndIncrement();
	}
}
